# /usr/bin/python3
# coding=utf-8
# @Time:2025/8/6 21:24
# @Author: cc
import time

from base.LoginBase import LoginBase
from base.ObjectMap import ObjectMap
from selenium.webdriver.common.by import By
from common.yaml_config import GetConfig
import requests


class LoginPage (LoginBase, ObjectMap) :
    def login_input_value(self, driver, input_placeholder, input_value) :
        '''
        登录页输入值
        :param driver:
        :param input_placeholder:
        :param input_value:
        :return:
        '''

        input_xpath = self.login_input (input_placeholder)
        # return driver.find_element_by_xpath (input_xpath).send_keys (input_value)
        return self.element_fill_value (driver, By.XPATH, input_xpath, input_value)

    def click_login(self, driver, button_name) :
        '''
        点击登陆
        :param driver:
        :param button_name:
        :return:
        '''

        button_xpath = self.login_button (button_name)
        # return driver.find_element_by_xpath (button_xpath).click ( )
        return self.element_click (driver, By.XPATH, button_xpath)

    def login(self, driver, user) :
        '''
        登陆
        :param driver: 浏览器驱动
        :param user: 登陆用户名和密码
        :return:
        '''
        # 跳转至url
        self.element_to_url (driver, "/login")
        # 获取用户名和密码
        username, password = GetConfig ( ).get_username_password (user)
        self.login_input_value (driver, "用户名", username)
        self.login_input_value (driver, "密码", password)
        self.click_login (driver, "登录")
        self.assert_login_success (driver)

    def api_login(self, driver, user) :
        '''
        通过api登录
        :param driver:
        :param user:
        :return:
        '''
        #    跳转到登录页面
        self.element_to_url (driver, "/login")
        # 获取用户名和密码
        username, password = GetConfig ( ).get_username_password (user)
        url = GetConfig ( ).get_url ( )
        data = {
            "user" : username,
            "password" : password
        }
        res = requests.post (url + '/api/user/login', json=data)
        token = res.json ( )["data"]["token"]
        js_script = f"window.sessionStorage.setItem('token','{token}')"
        driver.execute_script (js_script)
        time.sleep (2)
        self.element_to_url (driver, "/")

    def assert_login_success(self, driver) :
        '''
        验证是否登录成功
        :param driver:
        :return:
        '''
        success_xpath = self.login_success ( )
        self.element_appear (driver, By.XPATH, success_xpath, timeout=2)
